<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Admin\Actions\Grid;

use App\Models\User;
use Dcat\Admin\Support\LazyRenderable;

class ShowUserTree extends LazyRenderable
{
    public function render()
    {
        // 获取ID
        $id = $this->key;

        $user = User::query()
            ->select(['id', 'name', 'telephone', 'parent'])
            ->findOrFail($id);
        $total = 0;
        $tree = $user->queryDescendants()->with(['GroupOrderCount','performanceLevel'])
            ->select(['id', 'name', 'telephone', 'parent','agent_level'])
            ->get()->map(function ($item) use (&$total) {
                $item->GroupOrderCount = $item->GroupOrderCount->count();
                $total += $item->GroupOrderCount;
                $item->Level = $item->performanceLevel['name']??0;
                return $item;
            })->toTree();

        $user->total = $total;
        return admin_view('subtree', [
            'current' => $user,
            'tree' => $tree,
            'depth' => 1, // 初始展开层级
        ]);
    }
}
